<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog" width="60%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             label-width="100px"
             status-icon>

      <el-form-item label="名字：" prop="title">
        <el-input v-model="formData.title" :readonly="readonly" maxlength="128" placeholder="请输入名字" show-word-limit/>
      </el-form-item>

      <el-form-item label="面值：" prop="amount">
        <el-input-number v-model="formData.amount" :disabled="readonly" :min="0" :precision="2" :step="1" controls-position="right" placeholder="请输入面值"/>
      </el-form-item>

      <el-form-item label="使用限制：" prop="valid_type">
        <div style="width: 100%">
          <DictSelect v-model="formData.valid_type" :radio-group="true" :radio-button="false" dict-type="coupon_valid_type" @change="handleChangeValidType"/>
        </div>
        <div v-if="formData.valid_type > 0">
          <el-date-picker v-if="formData.valid_type == 1"
                          v-model="valid_time"
                          type="datetimerange"
                          range-separator="至"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          value-format="x"/>
          <el-input-number v-if="formData.valid_type == 2"
                           v-model="formData.valid_fixed_days"
                           :disabled="readonly" :min="0" :step="1" controls-position="right" placeholder="请输入天数" style="width: 15rem"/>
        </div>
      </el-form-item>

      <el-form-item label="是否限量：">
        <el-radio-group v-model="issued_limit" style="width: 100%" @change="handleChangeIssuedLimit">
          <el-radio :value="true">限量</el-radio>
          <el-radio :value="false">不限量</el-radio>
        </el-radio-group>
        <div v-if="issued_limit">
          <el-input-number v-model="formData.issued_count" :disabled="readonly" :min="0" :step="1" controls-position="right" placeholder="请输入发布数量" style="width: 15rem"/>
        </div>
      </el-form-item>

      <el-form-item label="使用规则：" prop="rule">
        <el-input v-model="formData.rule" :autosize="{ minRows: 2}"
                  :readonly="readonly"
                  maxlength="2048"
                  placeholder="请输入使用规则"
                  show-word-limit
                  type="textarea"/>
      </el-form-item>

      <el-form-item label="启用状态：" prop="status">
        <el-radio-group v-model="formData.status" :disabled="readonly">
          <el-radio-button :value="0">未开启</el-radio-button>
          <el-radio-button :value="1">正常</el-radio-button>
        </el-radio-group>
      </el-form-item>

    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['coupon:config:create', 'coupon:config:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { DictSelect } from '@/components/dict-select';
import { Coupon, couponInfo, couponSaveOrUpdate } from '@/api/api-coupon.ts';

defineOptions({name: 'coupon-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

/** 默认表单数据 */
const defaultForm: Coupon = <Coupon>{id: 0, status: 0, type: 1};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  title: [{required: true, message: '名称不能为空', trigger: 'blur'}],
  amount: [{required: true, message: '面值不能为空', trigger: 'blur'}],
  valid_type: [{required: true, message: '请设置使用限制', trigger: 'blur'}],
  status: [{required: true, message: '是否启用状态不能为空', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '现金消费券';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await couponInfo(id)
      formData.value = data;

      valid_time.value = [];
      if (formData.value.valid_type == 1) {
        valid_time.value = [formData.value.valid_time_from * 1000, formData.value.valid_time_to * 1000];
      }
      // 是否限量
      if (formData.value.issued_count && formData.value.issued_count > 0) {
        issued_limit.value = true;
      }
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    if (valid_time.value && valid_time.value.length == 2) {
      formData.value.valid_time_from = valid_time.value[0] / 1000
      formData.value.valid_time_to = valid_time.value[1] / 1000
    }
    // 提交数据
    couponSaveOrUpdate(formData.value, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  valid_time.value = [];
  issued_limit.value = false;
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

/** 时间范围 */
const valid_time = ref<any[]>([])

/** 使用限制被改变 */
const handleChangeValidType = () => {
  let val = formData.value.valid_type;
  if (val == 1) {
    formData.value.valid_fixed_days = 0
  } else if (val == 2) {
    valid_time.value = []
    formData.value.valid_time_from = 0
    formData.value.valid_time_to = 0
    formData.value.valid_fixed_days = 1
  } else {
    valid_time.value = []
    formData.value.valid_time_from = 0
    formData.value.valid_time_to = 0
    formData.value.valid_fixed_days = 0
  }
};

/** 发布限制 */
const issued_limit = ref(false);
const handleChangeIssuedLimit = () => {
  if (issued_limit.value) {
    formData.value.issued_count = undefined
  } else {
    formData.value.issued_count = 0
  }
};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select,
  .el-input-number {
    max-width: 15rem;
  }
}
</style>
